package com.uniview.controller;

import com.uniview.orm.model.City;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ReactiveHashOperations;
import org.springframework.data.redis.core.ReactiveListOperations;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.core.ReactiveSetOperations;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.*;

/**
 * @Author lux
 * @date: 2019/12/12
 * @desc: 使用注解的方式开发
 */
@RestController
public class StreamController {
    @Autowired
    ReactiveRedisTemplate reactiveRedisTemplate;

    @RequestMapping(value = "/save",produces = MediaType.APPLICATION_STREAM_JSON_VALUE)
    public Mono<String> save(){
        ReactiveSetOperations reactiveSetOperations =  reactiveRedisTemplate.opsForSet();
        Set<Map<String,Object>> testList = new HashSet<>();
        for (int i = 0; i <10 ; i++) {
            Map<String,Object> map = new HashMap<>();
            map.put("id",i);
            map.put("name","name"+1);
            testList.add(map);
        }
        reactiveSetOperations.add("test",testList).subscribe();
        return Mono.just("save success");
}

    @RequestMapping(value ="/getAll", produces = MediaType.APPLICATION_STREAM_JSON_VALUE)
    public Flux<Map<String,Object>> getAll(){
        ReactiveSetOperations reactiveSetOperations =  reactiveRedisTemplate.opsForSet();
        Flux<List<Map<String,Object>>> listMono =reactiveSetOperations.members("test");

        return listMono.flatMap(it -> Flux.fromIterable(it)).delayElements(Duration.ofSeconds(1));
//        Mono<List<Map<String,Object>>> listMap = reactiveSetOperations.pop("test");
//        return listMap.flatMapMany(Flux::fromIterable).delayElements(Duration.ofSeconds(10));
    }
}
